<template>
    <div class="task-form-container">
        <!-- 页面头部 -->
        <div class="page-header">
            <div class="header-content">
                <div class="header-left">
                    <h2>{{ isEdit ? '编辑任务' : '新增任务' }}</h2>
                </div>
                <div class="header-right">
                    <el-button @click="handleCancel">
                        <el-icon><ArrowLeft /></el-icon>
                        返回
                    </el-button>
                </div>
            </div>
        </div>

        <!-- 表单内容 -->
        <div class="form-content">
            <el-card shadow="never" class="form-card">
                <el-form
                    ref="taskFormRef"
                    :model="formData"
                    :rules="formRules"
                    label-width="120px"
                    class="task-form"
                >
                    <div class="form-layout">
                        <!-- 左侧表单 -->
                        <div class="form-left">
                            <!-- 任务代码 -->
                            <el-form-item label="任务代码:" prop="taskCode">
                                <el-input
                                    v-model="formData.taskCode"
                                    placeholder="输入任务代码"
                                    style="width: 300px"
                                />
                            </el-form-item>

                            <!-- 任务名称 -->
                            <el-form-item label="任务名称:" prop="taskName">
                                <el-input
                                    v-model="formData.taskName"
                                    placeholder="输入任务名称"
                                    style="width: 300px"
                                />
                            </el-form-item>

                            <!-- 任务介绍 -->
                            <el-form-item label="任务介绍:" prop="taskDescription">
                                <el-input
                                    v-model="formData.taskDescription"
                                    type="textarea"
                                    :rows="3"
                                    placeholder="请输入任务介绍"
                                    style="width: 400px"
                                />
                            </el-form-item>

                            <!-- 参与条件 -->
                            <el-form-item label="参与条件:" prop="memberLevelIds">
                                <el-checkbox-group v-model="formData.memberLevelIds">
                                    <el-checkbox value="1">会员等级1</el-checkbox>
                                    <el-checkbox value="2">会员等级2</el-checkbox>
                                    <el-checkbox value="3">会员等级3</el-checkbox>
                                    <el-checkbox value="4">会员等级4</el-checkbox>
                                    <el-checkbox value="5">会员等级5</el-checkbox>
                                    </el-checkbox-group>
                            </el-form-item>

                            <!-- 任务类型 -->
                            <el-form-item label="任务类型:" prop="taskType">
                                <el-select v-model="formData.taskType" placeholder="请选择..." style="width: 200px">
                                    <el-option label="浏览文章" value="1" />
                                    <el-option label="观看视频" value="2" />
                                    <el-option label="购买商品" value="3" />
                                    <el-option label="购买服务" value="4" />
                                    <el-option label="邀请" value="5" />
                                    <el-option label="签到" value="6" />
                                </el-select>
                            </el-form-item>

                            <!-- 完成数量 -->
                            <el-form-item label="完成数量:" prop="completionQuantity">
                                <el-input-number
                                    v-model="formData.completionQuantity"
                                    :min="1"
                                    :max="999"
                                    placeholder="输入需要完成的数量"
                                    style="width: 200px"
                                />
                            </el-form-item>
                        </div>

                        <!-- 右侧表单 -->
                        <div class="form-right">
                            <!-- 任务周期 -->
                            <el-form-item label="任务周期:" prop="taskCycle">
                                <el-select v-model="formData.taskCycle" placeholder="请选择..." style="width: 200px">
                                    <el-option label="按日" value="1" />
                                    <el-option label="按周" value="2" />
                                    <el-option label="活动" value="3" />
                                </el-select>
                            </el-form-item>

                            <!-- 奖励类型 -->
                            <el-form-item label="奖励类型:" prop="rewardType">
                                <el-select v-model="formData.rewardType" placeholder="请选择奖励类型" style="width: 200px">
                                    <el-option label="积分" value="1" />
                                    <el-option label="道具" value="2" />
                                    <el-option label="积分+道具" value="3" />
                                </el-select>
                            </el-form-item>

                            <!-- 奖励配置 -->
                            <el-form-item label="奖励配置:" prop="rewardConfig" v-if="formData.rewardType">
                                        <el-input 
                                    v-model="formData.rewardConfig"
                                    type="textarea"
                                    :rows="3"
                                    placeholder="请输入奖励配置JSON"
                                    style="width: 300px"
                                />
                            </el-form-item>

                            <!-- 是否限时 -->
                            <el-form-item label="是否限时:" prop="isTimeLimited">
                                <el-radio-group v-model="formData.isTimeLimited">
                                    <el-radio :value="false">不限时</el-radio>
                                    <el-radio :value="true">限时</el-radio>
                                </el-radio-group>
                            </el-form-item>

                            <!-- 时间设置 -->
                            <el-form-item label="开始时间:" prop="startTime" v-if="formData.isTimeLimited">
                                        <el-date-picker
                                    v-model="formData.startTime"
                                    type="datetime"
                                    placeholder="选择开始时间"
                                    style="width: 200px"
                                />
                            </el-form-item>

                            <el-form-item label="结束时间:" prop="endTime" v-if="formData.isTimeLimited">
                                        <el-date-picker
                                    v-model="formData.endTime"
                                    type="datetime"
                                    placeholder="选择结束时间"
                                    style="width: 200px"
                                />
                            </el-form-item>


                            <!-- 语言代码 -->
                            <el-form-item label="语言代码:" prop="language">
                                <el-select v-model="formData.language" placeholder="请选择" style="width: 200px">
                                    <el-option label="中文" value="zh-CN" />
                                    <el-option label="英文" value="en-US" />
                                </el-select>
                            </el-form-item>
                        </div>
                    </div>

                    <!-- 操作按钮 -->
                    <el-form-item>
                        <div class="form-actions">
                            <el-button @click="handleCancel">取消</el-button>
                            <el-button type="primary" @click="handleSubmit">保存</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>

    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ArrowLeft } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { createTask, updateTask, getTaskDetail } from '@/api/system/task'

const route = useRoute()
const router = useRouter()

// 表单引用
const taskFormRef = ref<FormInstance>()

// 是否为编辑模式
const isEdit = computed(() => !!route.params.id)


// 表单数据
const formData = reactive({
    taskCode: '',
    taskName: '',
    taskDescription: '',
    taskType: '',
    completionQuantity: '',
    rewardType: '',
    rewardConfig: '',
    memberLevelIds: [] as string[],
    isTimeLimited: false,
    startTime: '',
    endTime: '',
    taskCycle: '',
    language: ''
})

// 表单验证规则
const formRules = reactive<FormRules>({
    taskCode: [
        { required: true, message: '请输入任务代码', trigger: 'blur' },
        { min: 1, max: 50, message: '长度在1到50个字符', trigger: 'blur' }
    ],
    taskName: [
        { required: true, message: '请输入任务名称', trigger: 'blur' },
        { min: 2, max: 100, message: '长度在2到100个字符', trigger: 'blur' }
    ],
    taskDescription: [
        { required: true, message: '请输入任务介绍', trigger: 'blur' },
        { min: 2, max: 100, message: '长度在2到100个字符', trigger: 'blur' }
    ],
    memberLevelIds: [
        { required: true, message: '请选择参与条件', trigger: 'change' }
    ],
    taskType: [
        { required: true, message: '请选择任务类型', trigger: 'change' }
    ],
    completionQuantity: [
        { required: true, message: '请输入完成数量', trigger: 'blur' },
        { type: 'number', min: 1, message: '完成数量必须大于0', trigger: 'blur' }
    ],
    taskCycle: [
        { required: true, message: '请选择任务周期', trigger: 'change' }
    ],
    rewardType: [
        { required: true, message: '请选择奖励类型', trigger: 'change' }
    ],
    language: [
        { required: true, message: '请选择语言', trigger: 'change' }
    ]
})

// 取消操作
const handleCancel = () => {
    router.go(-1)
}

// 提交表单
const handleSubmit = async () => {
    if (!taskFormRef.value) return

    try {
        await taskFormRef.value.validate()
        
        // 构建提交数据
        const submitData = {
            taskCode: formData.taskCode,
            taskName: formData.taskName,
            taskDescription: formData.taskDescription,
            taskType: parseInt(formData.taskType),
            completionQuantity: parseInt(formData.completionQuantity),
            rewardType: parseInt(formData.rewardType),
            rewardConfig: formData.rewardConfig,
            memberLevelIds: formData.memberLevelIds,
            isTimeLimited: formData.isTimeLimited,
            startTime: formData.startTime,
            endTime: formData.endTime,
            taskCycle: parseInt(formData.taskCycle),
            language: formData.language
        }
        
        console.log('提交的数据:', submitData)
        
        let res: any
        if (isEdit.value) {
            // 编辑模式
            res = await updateTask(submitData)
        } else {
            // 新增模式
            res = await createTask(submitData)
        }
        
        const responseData = res as any
        if (responseData && responseData.code === 200) {
            ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
        setTimeout(() => {
            router.push('/task-list')
        }, 1000)
        } else {
            const errorMsg = (responseData && responseData.msg) || (isEdit.value ? '编辑失败' : '新增失败')
            ElMessage.error(errorMsg)
        }
    } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('请检查表单信息')
    }
}

// 移除道具（已废弃，保留兼容性）
const removeProp = (index: number) => {
    // 已废弃的方法
}

// 全选道具（已废弃，保留兼容性）
const handleSelectAll = (checked: boolean) => {
    // 已废弃的方法
}

// 确认道具选择（已废弃，保留兼容性）
const confirmPropSelection = () => {
    // 已废弃的方法
}

// 加载任务数据（编辑模式）
const loadTaskData = async () => {
    if (isEdit.value) {
        try {
            const id = route.params.id as string
            const res = await getTaskDetail(id)
            const responseData = res as any
            
            if (responseData && responseData.code === 200 && responseData.data) {
                const data = responseData.data
        Object.assign(formData, {
                    taskCode: data.taskCode || '',
                    taskName: data.taskName || '',
                    taskDescription: data.taskDescription || '',
                    taskType: data.taskType?.toString() || '',
                    completionQuantity: data.completionQuantity?.toString() || '',
                    rewardType: data.rewardType?.toString() || '',
                    rewardConfig: data.rewardConfig || '',
                    memberLevelIds: data.memberLevelIds || [],
                    isTimeLimited: data.isTimeLimited || false,
                    startTime: data.startTime || '',
                    endTime: data.endTime || '',
                    taskCycle: data.taskCycle?.toString() || '',
                    language: data.language || ''
                })
                
                console.log('加载的任务数据:', data)
            } else {
                const errorMsg = (responseData && responseData.msg) || '获取任务详情失败'
                ElMessage.error(errorMsg)
            }
        } catch (error) {
            console.error('获取任务详情失败:', error)
            ElMessage.error('获取任务详情失败，请稍后重试')
        }
    }
}

onMounted(() => {
    loadTaskData()
})
</script>

<style scoped>
.task-form-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

/* 页面头部 */
.page-header {
    margin-bottom: 20px;
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left h2 {
    margin: 0;
    color: #303133;
    font-size: 24px;
    font-weight: 600;
    border-bottom: 2px solid #20b2aa;
    padding-bottom: 8px;
}

.header-right {
    display: flex;
    gap: 12px;
}

/* 表单内容 */
.form-content {
    /* max-width: 1200px; */
}

.form-card {
    border-radius: 8px;
    background-color: #fff;
}

.task-form {
    padding: 20px;
}

.form-layout {
    display: flex;
    gap: 40px;
}

.form-left {
    flex: 1;
}

.form-right {
    flex: 1;
    border-left: 1px solid #ebeef5;
    padding-left: 40px;
}

.form-hint {
    color: #f56c6c;
    font-size: 12px;
    margin-top: 5px;
    margin-left: 8px;
}

.conditions-section {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.reward-section {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.reward-item {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
}

.selected-props {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-left: 10px;
}

.time-section {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.date-range {
    display: flex;
    align-items: center;
}

.form-actions {
    display: flex;
    gap: 12px;
    margin-top: 20px;
    justify-content: center;
}

/* Element Plus 组件样式覆盖 */
:deep(.el-card__body) {
    padding: 0;
}

:deep(.el-form-item) {
    margin-bottom: 24px;
}

:deep(.el-form-item__label) {
    font-weight: 500;
    color: #303133;
}

:deep(.el-input__wrapper) {
    border-radius: 4px;
}

:deep(.el-select .el-input__wrapper) {
    border-radius: 4px;
}

:deep(.el-button) {
    border-radius: 4px;
}

:deep(.el-checkbox-group) {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .task-form-container {
        padding: 10px;
    }
    
    .header-content {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;
    }
    
    .form-content {
        max-width: 100%;
    }
    
    .task-form {
        padding: 15px;
    }
    
    .form-layout {
        flex-direction: column;
        gap: 20px;
    }
    
    .form-right {
        border-left: none;
        border-top: 1px solid #ebeef5;
        padding-left: 0;
        padding-top: 20px;
    }
    
    .reward-item {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
    }
    
    .date-range {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }
}
</style>
